﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;

namespace WinFormsApp1.Common
{
    public class HttpClientHelper
    {
        public async static Task<K> RequestUrl<T, K>(string url, string method, MethodType type, T data = default!)
        {
            using HttpClient httpClient = new HttpClient();
            string baseUrl = url;
            httpClient.BaseAddress = new Uri(baseUrl);

            //httpClient.DefaultRequestHeaders.Add("Accept", "application/json");


            HttpResponseMessage response = null;
            var context = string.Empty;
            switch (type)
            {
                case MethodType.GET:
                    response = await httpClient.GetAsync(method);
                    if (response.IsSuccessStatusCode)
                    {
                        context = await response.Content.ReadAsStringAsync();
                        var list = Newtonsoft.Json.JsonConvert.DeserializeObject<K>(context);
                        return list;
                    }
                    break;
                case MethodType.POST:
                    var responsePost = await httpClient.PostAsJsonAsync(method, data);
                    if (responsePost.IsSuccessStatusCode)
                    {
                        context = await responsePost.Content.ReadAsStringAsync();
                        var list = Newtonsoft.Json.JsonConvert.DeserializeObject<K>(context);
                        return list;
                    }
                    break;
                case MethodType.PUT:
                    break;
                case MethodType.DELETE:
                    break;
            }
             return default!;
        }

        public enum MethodType
        {
            GET,
            POST,
            PUT,
            DELETE,
        }
    }
}
